<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
</head>
<body>

<div>

    用户名:<input type="text" id="username"><br>
    密码:<input type="password" id="pwd"><br>

    头像：
    <input type="file" id="imageUrl" > <br>
    <input type="hidden" id="hd-imgUrl" > <br>
    <img src="" width="100" id="img-url"><br>
    性别:
    <input type="radio" name="sex" value="0"> 男
    <input type="radio" name="sex" value="1"> 女
    <input type="radio" name="sex" value="2"> 保密

    <br>
    身份：<select  id="identity">
            <option value="1">学生</option>
            <option value="2">老师</option>
            <option value="0">保密</option>
        </select><br>
    爱好:
    <input type="checkbox" name="hobby" value="1"> 篮球
    <input type="checkbox" name="hobby" value="2"> 足球
    <input type="checkbox" name="hobby" value="3"> 乒乓球
    <input type="checkbox" name="hobby" value="4"> 羽毛球

    <br>


    <button id="btn">注册</button>

</div>
</body>
</html>
<script src="./js/axios.min.js"></script>

<script>


    //上传头像
    document.getElementById("imageUrl").onchange = function (e) {

        //上传头像
        let formData = new FormData();


        formData.append('file',e.target.files[0]);


        axios.post('/file/upload',formData)
            .then(res => {

                document.getElementById("img-url").src = res.data
                document.getElementById("hd-imgUrl").value = res.data

            });



    }


    document.getElementById("btn")
        .onclick = function () {

        const userName = document.getElementById("username").value
        const password = document.getElementById("pwd").value
        const identity = document.getElementById("identity").value
        const imgUrl = document.getElementById("hd-imgUrl").value
        //获取单选按钮的值
        const sex = document
            .querySelector('input[name="sex"]:checked').value
        const hobby = []
        //获取复选按钮的值
        //简便写法

        for (let i = 0; i < document.getElementsByName("hobby").length; i++) {
            if (document.getElementsByName("hobby")[i].checked){
                hobby.push(document.getElementsByName("hobby")[i].value)
            }
        }



        const url = '/user/register'
        const data = {
            'username':userName,
            'password' : password,
            'identity' : identity,
            'sex': sex,
            'hobby' : hobby,
            'imageUrl': imgUrl
        }
        axios.post(url , data)
            .then(res => {

                const R = res.data

                console.log(R)

                if (R.code === 200){



                    localStorage.setItem('user',JSON.stringify(R.data))
                    location.href = 'index.html'
                }else {
                    alert(R.msg)
                }
            })

    }


</script>